from django.contrib import admin

from commodity.models import CommodityInfos
from .models import *
# Register your models here.
# admin.site.register(CartInfos)
# admin.site.register(OrderInfos)
# 注册CartInfos模型到admin管理，并自定义他在admin中的展示配置
@admin.register(CartInfos)
class CartInfosAdmin(admin.ModelAdmin):
    # 设置在列表页显示字段是id和quantity
    list_display = ['id', 'quantity']

@admin.register(OrderInfos)
class OrderInfosAdmin(admin.ModelAdmin):
    list_display = ['id', 'price', 'created', 'state']
    # 按照state字段来进行过滤
    list_filter = ['state']
    # 设置按照created日期字段进行层级导航
    date_hierarchy = 'created'
# @admin.register(CommodityInfos)
# class CommodityInfosAdmin(admin.ModelAdmin):
#     list_display =  [x for x in list(CommodityInfos._meta._forward_fields_map.keys())]
#     # 新增行
#     list_display.append('colored_name')
#     def get_readonly_fields(self, request, obj = None):
#         if request.user.is_superuser:
#             self.readonly_fields = []
#         else:
#             self.readonly_fields = ['types']
#         return self.readonly_fields
# 根据当前的用户名设置数据访问权限
def get_queryset(self, request):
    # 获取父类ModelAdmin的函数get_queryset()生成的模型查询对象，查询全数据
    qs = super().get_queryset(request)
    # 判断当前用户角色，如果是超级管理员，返回全部数据，否则返回id小于2的数据
    if request.user.is_superuser:
        return qs
    else:
        return qs.filter(id__lt=2)
def save_model(self, request, obj, form, change):
    """
    对数据的修改实现日志记录
    request:当前用户的请求对象
    obj:模型的数据对象
    form:模型表单，是Django自动创建的模型表单
    change:判断当前请求是来自于数据修改页（True）还是数据新增页False
    """
    if change:
        # 获取当前用户名
        user = request.user.username
        # 使用模型获取数据,pk代表有主键属性的字段
        name = self.model.objects.get(pk=obj.pk).name
        # 使用表达获取数据
        types = form.cleaned_data['types']
        # 写入日志文件
        f = open("d://log.txt", 'a', encoding='utf-8')
        f.write(name + "商品类型：" + types + "被" + user + "修改" + '\r\n')
        f.close()
    else:
        pass
    super().save_model(request, obj, form, change)
def get_datas(self, request, queryset):
    """
        queryset:代表已经被勾选的数据对象
        """
    temp = []
    for d in queryset:
        t = [d.name, d.types, str(d.discount)]
        temp.append(t)
        f = open("d://data.txt", 'a', encoding='utf-8')
    for t in temp:
        f.write(",".join(t) + '\r\n')
        f.close()

    self.message_user(request, "数据导出成功")
    # 设置函数的显示名称
    get_datas.short_description = "导出所选数据"
# 添加到acton中
actions = ['get_datas']